<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button
          type="primary"
          size="mini"
          @click="showAdd = true"
        >添加角色</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="角色" width="200px" align="center">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.name"
              size="mini"
            />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="启用" width="200px" align="center">
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{
              row.state === 0 ? "未启用" : row.state === 1 ? "已启用" : "无"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template v-slot="{ row }">
            <el-input
              v-if="row.isEdit"
              v-model="row.editRow.description"
              type="textarea"
              size="mini"
              :rows="2"
            />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button
                type="primary"
                size="mini"
                @click="editRole(row)"
              >确定</el-button>
              <el-button
                size="mini"
                @click="row.isEdit = false"
              >取消</el-button>
            </template>
            <template v-else>
              <el-button
                type="text"
                size="mini"
                @click="allotPermission(row.id)"
              >分配权限</el-button>
              <el-button
                type="text"
                size="mini"
                @click="showEdit(row)"
              >编辑</el-button>
              <el-popconfirm
                title="确定删除此角色吗？"
                @onConfirm="delRole(row.id)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="mini"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page.sync="pageParams.page"
          @current-change="getRoleList"
        />
      </el-row>
      <el-dialog
        width="500px"
        :visible.sync="showAdd"
        title="新增角色"
        @close="addClose"
      >
        <el-form
          ref="addForm"
          label-width="120px"
          :model="addForm"
          :rules="rules"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="addForm.name" style="width: 300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch
              v-model="addForm.state"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="addForm.description"
              type="textarea"
              :rows="3"
              style="width: 300px"
              size="mini"
            />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button
                  type="primary"
                  size="mini"
                  @click="addSubmit"
                >确定</el-button>
                <el-button size="mini" @click="addClose">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-dialog
        :visible.sync="permissionDialog"
        title="分配权限"
        @close="assignPermClose"
      >
        <el-tree
          ref="permTree"
          :data="permissionList"
          node-key="id"
          :props="{ label: 'name' }"
          check-strictly
          default-expand-all
          show-checkbox
        />
        <template #footer>
          <el-row type="flex" justify="center">
            <el-button
              type="primary"
              size="mini"
              @click="confirmPerm"
            >确定</el-button>
            <el-button size="mini" @click="assignPermClose">取消</el-button>
          </el-row>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  getRoleList,
  addRole,
  editRole,
  delRole,
  getRoleDetail,
  assignPerm
} from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showAdd: false,
      addForm: {
        name: '',
        description: '',
        state: 1
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      permissionDialog: false,
      permissionList: [],
      currentId: null
    }
  },
  created() {
    this.getRoleList()
    this.getPermissionList()
  },
  methods: {
    async getRoleList() {
      const { total, rows } = await getRoleList({ ...this.pageParams })
      this.tableData = rows.map((item) => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
        return item
      })
      this.pageParams.total = total
    },
    addSubmit() {
      this.$refs.addForm.validate(async(isOK) => {
        if (isOK) {
          await addRole({ ...this.addForm })
          this.$message.success('添加成功')
          this.getRoleList()
          this.addClose()
        }
      })
    },
    addClose() {
      this.$refs.addForm.resetFields()
      this.addForm.state = 1
      this.showAdd = false
    },
    showEdit(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async editRole(row) {
      if (row.name && row.description) {
        await editRole({ ...row.editRow, id: row.id })
        Object.assign(row, { ...row.editRow, isEdit: false })
        this.$message.success('更新角色成功')
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async delRole(id) {
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.tableData.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    async allotPermission(id) {
      const { permIds } = await getRoleDetail(id)
      this.currentId = id
      this.permissionDialog = true
      const tree = this.$refs.permTree
      tree
        ? tree.setCheckedKeys(permIds)
        : this.$nextTick(() => {
          this.$refs.permTree.setCheckedKeys(permIds)
        })
    },
    async getPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transListToTree(res, 0)
    },
    assignPermClose() {
      this.permissionDialog = false
      this.permIds = []
    },
    async confirmPerm() {
      const permIds = this.$refs.permTree.getCheckedKeys()
      await assignPerm({
        id: this.currentId,
        permIds
      })
      this.$message.success('角色分配权限成功')
      this.assignPermClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
